<?php

class Safety_LoginController extends App_Controller_Action
{

	public function init() {
		$this->_helper->layout()->setLayout('login');
	}
	
	/**
	 * The default action - show the home page
	 */
	public function indexAction() {
		$this->_forward('login');
	}

	public function loginAction() {
		$this->view->title = 'Log In';
	}
	
	public function logoutAction() {
		$auth = Zend_Auth::getInstance();
		$auth->clearIdentity();
		Zend_Session::forgetMe();
		$this->_helper->redirector('login', 'login', 'safety');
	}
	
	public function identifyAction() {
		$this->_helper->viewRenderer->setNoRender(true);
		if ($this->getRequest()->isPost()) {
			$formData = $this->getFormData();
			if ( empty($formData['username']) || empty($formData['password']) ) {
				// TODO: mostrar mensaje que falta el user y password al usuario
			} else {
				// do the authentication
				$authAdapter = $this->getAuthAdapter($formData);
				$auth = Zend_Auth::getInstance();
				$result = $auth->authenticate($authAdapter);
				if ( $result->isValid() ) {
					$data = $authAdapter->getResultRowObject(null,array('pw', 'created'));
					$auth->getStorage()->write($data);
					if ($this->_hasParam('rememberme') && $this->_getParam('rememberme')) {
		            	// Receive Zend_Session_Namespace object
			            require_once('Zend/Session/Namespace.php');
			            $session = new Zend_Session_Namespace('Zend_Auth');
			            // Set the time of user logged in 24 horas
			            $session->setExpirationSeconds(24*3600);
			            Zend_Session::rememberMe();
		            }
		            $authNamespace = new Zend_Session_Namespace('Cms_Auth');
// 		            $this->_redirect('/');
		            $this->_helper->redirector('index', 'dashboard', 'admin');
					return;
				} else {
					switch ($result->getCode()) {
				        case Zend_Auth_Result::FAILURE :
				            $this->_messenger->addError(_('Ha ocurrido un error el servidor al validar el usuario, por favor intentelo de nuevo.'));
				            break;
				        case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID :
				            $this->_messenger->addError(_('The password is invalid.'));
				            break;
				        case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND :
				            $this->_messenger->addError(_("The user doesn't exist."));
				            break;
				        case Zend_Auth_Result::FAILURE_UNCATEGORIZED :
				            $this->_messenger->addError(_('Ha ocurrido un error inesperado en el servidor, por favor consulte con su administrador.'));
				            break;
				        default :
				        	$this->_messenger->addError(_('The user or password is invalid.'));
				        	break;
				    }
				}
			}
		}
		$this->_helper->redirector('index', 'login', 'safety');
	}
	
	protected function getAuthAdapter($formData) {
		$authAdapter = new App_Auth_Adapter_Doctrine($this->_entityManager);
		$authAdapter->setEntityName('model\User')
					->setIdentityField('name')
					->setCredentialField('pw');
		$authAdapter->setIdentity($formData['username']);
		$authAdapter->setCredential($formData['password']);
		
		return $authAdapter;
	}
	
	/**
	 * 
	 */
	private function getFormData() {
        $data = array();
        $filterChain = new Zend_Filter;
        $filterChain->addFilter(new Zend_Filter_StripTags);
        $filterChain->addFilter(new Zend_Filter_StringTrim);
        
        $data['username'] = $filterChain->filter(
            $this->getRequest()->getPost('username')
        );
        $data['password'] = $filterChain->filter(
            $this->getRequest()->getPost('password')
        );

        return $data;
    }
}

